package com.think.teaching.utils.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.input.ReaderInputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.think.common.model.Result;
import com.think.common.model.ResultCode;
import com.think.common.utils.JSonUtil;
import com.think.teaching.utils.service.FileUploadService;

@RestController
@ResponseBody
@RequestMapping("v1")
public class FileUploadController {

	@Value("${file.basePath}")
	private String basePath;

	@Value("${file.baseUrl}")
	private String baseUrl;
	
	@Autowired
	private FileUploadService fileUploadService;


	public static void GeneratorUnityConfig(String projDir) {
		File files = new File(projDir);
		if (files.exists() && files.isDirectory()) {
			File[] fs = files.listFiles();
			for (int i = 0; i < fs.length; i++) {
				String name = fs[i].getPath();
				if (name.endsWith(".json")) {

					try {
						FileReader fr = new FileReader(fs[i]);
						char[] byteArray = new char[(int) fs[i].length()];
						int size = fr.read(byteArray);
						Map<String, Object> map = JSonUtil.getJsonObj(new String(byteArray));
						System.err.println(map.get("productName"));
						fr.close();
					} catch (Exception ex) {

					} finally {
						// : handle finally clause
					}
					break;
				}
			}
		}
	}

	public static void unZip(File zipFile, String outDir) throws IOException {

		File outFileDir = new File(outDir);
		if (!outFileDir.exists()) {
			boolean isMakDir = outFileDir.mkdirs();
			if (!isMakDir) {
				throw new IOException("创建文件夹失败");
			}
		}

		ZipFile zip = new ZipFile(zipFile);
		for (Enumeration enumeration = zip.getEntries(); enumeration.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) enumeration.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);

			if (entry.isDirectory()) { // 处理压缩文件包含文件夹的情况
				File fileDir = new File(outDir + zipEntryName);
				fileDir.mkdir();
				continue;
			}

			File file = new File(outDir, zipEntryName);
			file.createNewFile();
			OutputStream out = new FileOutputStream(file);
			byte[] buff = new byte[1024];
			int len;
			while ((len = in.read(buff)) > 0) {
				out.write(buff, 0, len);
			}
			in.close();
			out.close();
		}
		zip.close();
		
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Result uploadFile(@RequestParam("filename") MultipartFile file, @RequestParam("type") Integer type,
			HttpServletRequest request, HttpServletResponse response) {
		Result result = null;
		// 判断文件是否为空
		if (file.isEmpty()) {
			result = Result.failure(ResultCode.PARAM_FILE_EMPTY);
		} else {
			// 获取文件名
			String fileName = file.getOriginalFilename();

//            System.out.print("上传的文件名为: "+fileName+"\n");
			String name = fileName;
			fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
			System.out.print("（加个时间戳，尽量避免文件名称重复）保存的文件名为: " + fileName + "\n");

			// 加个时间戳，尽量避免文件名称重复
			String path = "E:/fileUpload/" + fileName;
			// String path = "E:/fileUpload/" + new
			// SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
			// 文件绝对路径
			System.out.print("保存文件绝对路径" + path + "\n");
			String url = "http://localhost:8081/fileUpload/others/" + fileName;// 本地运行项目
			switch (type) {
			case 1:
				path = basePath + "images/" + fileName;
				url = "images/" + fileName;
				break;
			case 2:
				path = basePath + "videos/" + fileName;
				url = "videos/" + fileName;
				break;
			case 3:
				path = basePath + "documents/" + fileName;
				url = "documents/" + fileName;
				break;
			case 4:
				path = basePath + "others/" + fileName;
				url = "others/" + fileName;
				break;

			default:
				path = basePath + "others/" + fileName;
				url = "others/" + fileName;
				break;
			}
			// 创建文件路径
			File dest = new File(path);

			// 判断文件是否已经存在
			if (dest.exists()) {
				result = Result.failure(ResultCode.FILE_ALREADY_EXITS);
			}

			// 判断文件父目录是否存在
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdir();
			}

			try {
				// 上传文件
				file.transferTo(dest); // 保存文件
				result = Result.success(url);

			} catch (IOException e) {
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR, e.getLocalizedMessage());
			}
		}
		return result;
	}

	
	@RequestMapping(value = "/upload/zip", method = RequestMethod.POST)
	public Result uploadZipFileAndUnZip(@RequestParam("filename") MultipartFile file,@RequestParam("course")Integer course, HttpServletRequest request,
			HttpServletResponse response) {
		Result result = null;
		// 判断文件是否为空
		if (file.isEmpty()) {
			result = Result.failure(ResultCode.PARAM_FILE_EMPTY);
		} else {
			// 获取文件名
			
			String fileName = file.getOriginalFilename();
			if (!fileName.endsWith(".zip")) {
				result = Result.failure(ResultCode.FILE_NOT_ZIP);
				return result;
			}
//            System.out.print("上传的文件名为: "+fileName+"\n");
			String name = fileName;
			fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
			String basePath = "E:/fileUpload/" + "unzips/";
			String path = basePath + fileName;
			String url = baseUrl + "unzips/" + fileName;
			// 创建文件路径
			File dest = new File(path);
			// 判断文件是否已经存在
			if (dest.exists()) {
				result = Result.failure(ResultCode.FILE_ALREADY_EXITS);
			}

			// 判断文件父目录是否存在
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdir();
			}

			try {
				// 上传文件
				file.transferTo(dest); // 保存文件
				unZip(dest, path.substring(0, path.length() - 4) + "/");
				url = url.substring(0, url.length() - 4);
				fileUploadService.UploadZip(path, file.getOriginalFilename().substring(0, file.getOriginalFilename().length() - 4));
				if (!dest.delete()) {
					System.err.println("删除文件失败");
				}
				result = Result.success(url);

			} catch (IOException e) {
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR, e.getLocalizedMessage());
			}
		}
		return result;
	}

	@RequestMapping(value = "/upload/proj", method = RequestMethod.POST)
	public Result uploadZipProj(@RequestParam("filename") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		Result result = null;
		// 判断文件是否为空
		if (file.isEmpty()) {
			result = Result.failure(ResultCode.PARAM_FILE_EMPTY);
		} else {
			// 获取文件名
			String fileName = file.getOriginalFilename();
			if (!fileName.endsWith(".zip")) {
				result = Result.failure(ResultCode.FILE_NOT_ZIP);
				return result;
			}
			fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;

			String path = "E:/fileUpload/" + "vlabs/" + fileName;
			String url = baseUrl + "vlabs/" + fileName;
			// 创建文件路径
			File dest = new File(path);
			// 判断文件是否已经存在
			if (dest.exists()) {
				result = Result.failure(ResultCode.FILE_ALREADY_EXITS);
			}

			// 判断文件父目录是否存在
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdir();
			}

			try {
				// 上传文件
				file.transferTo(dest); // 保存文件
				unZip(dest, path.substring(0, path.length() - 4) + "/");
				url = url.substring(0, url.length() - 4);
				GeneratorUnityConfig(path.substring(0, path.length() - 4) + "/Build");
				result = Result.success(url);

			} catch (IOException e) {
				result = Result.failure(ResultCode.SYSTEM_INNER_ERROR, e.getLocalizedMessage());
			}
		}
		return result;
	}
}
